package com.bootssm.controller;

import com.bootssm.entity.*;
import com.bootssm.service.FinanceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/finance")
public class FinanceController {
    @Autowired
    FinanceService financeService;

    @PostMapping("/findAll")
    public PageView<Finance> finAll(@RequestBody FinanceVO financeVO){
        Integer page = financeVO.getPage(); //拿到前端页码
        int start = (page - 1) * financeVO.getSize();//计算出来开始位置
        //把开始位置设置到studentVO中
        financeVO.setStart(start);

        //获取总条数
        Integer count = financeService.getCount(financeVO);
        List<Finance> financeList = financeService.findAll(financeVO);

        PageView<Finance> pageView = new PageView<>();
        pageView.setDataList(financeList); //数据
        pageView.setCount(count); //总条数

        System.out.println(pageView.getDataList()+" "+pageView.getCount());

        return pageView;
    }

    @PostMapping("/deleteById")
    public Result deleteById(@RequestBody Finance finance){
        //根据ID删除数据库
        String id = finance.getCountid(); //得到传递过来的ID
        if(id==null){
            return new Result("500","删除失败");
        }
        financeService.deleteById(id);

        return new Result("200","删除成功");
    }

    @PostMapping("/update")
    public Result update(@RequestBody Finance finance){

        try{
            financeService.update(finance);
        }catch (Exception e){
            e.printStackTrace();
            return new Result("500","修改失败");
        }

        return new Result("200","修改成功");
    }

    @PostMapping("/save")
    public Result save(@RequestBody Finance finance){

        try{
            financeService.save(finance);
        }catch (Exception e){
            e.printStackTrace();
            return new Result("500","保存失败");
        }

        return new Result("200","保存成功");
    }
}
